package club.kingyin.easycache.method.core;

import club.kingyin.easycache.cache.CacheAdapter;
import club.kingyin.easycache.cache.ValueSerializer;
import club.kingyin.easycache.cache.inner.InnerCache;
import club.kingyin.easycache.component.handler.Serializer;
import com.github.houbb.cache.core.support.load.CacheLoads;
import com.github.houbb.cache.core.support.persist.CachePersists;

import java.io.File;

public class DefaultCacheEnhancer extends CacheEnhancer {
    @Override
    protected void init() {
        loadCacheEngineAndSerializer();
    }

    private String path;

    public DefaultCacheEnhancer() {
        super();
    }

    public DefaultCacheEnhancer(CacheAdapter cacheAdapter, ValueSerializer serializer) {
        setDatabase(cacheAdapter);
        setSerializer(serializer);
    }

    public DefaultCacheEnhancer(String path, ValueSerializer serializer) {
        setSerializer(serializer);
        this.path = path;
    }

    public DefaultCacheEnhancer(String path) {
        this.path = path;
    }

    public DefaultCacheEnhancer(CacheAdapter cacheAdapter) {
        setDatabase(cacheAdapter);
    }


    private void loadCacheEngineAndSerializer() {
        if (!isLoadSerializer()) {
            setSerializer(Serializer.GSON);
        }
        if (!isLoadDatabase()) {
            setDatabase(structureDefaultCacheEngine());
        }
    }

    private boolean isLoadSerializer() {
        return getSerializer() != null;
    }

    private CacheAdapter structureDefaultCacheEngine() {
        InnerCache.Builder builder = new InnerCache.Builder();
        if (new File(getPath()).exists()) {
            // 需要加载数据
            builder.load(CacheLoads.dbJson(getPath()));
        }
        InnerCache adapter = builder
                .persist(CachePersists.dbJson(getPath())).build();
        adapter.setSerializer(getSerializer());
        return adapter;
    }

    boolean isLoadDatabase() {
        return getDatabase() != null;
    }

    public CacheAdapter getDatabase() {
        return this.database;
    }

    public String getPath() {
        return path = path == null ? defaultDbPath() : path;
    }

    public String defaultDbPath() {
        return System.getProperty("user.dir") + "/src/main/resources/easycache.rdb";
    }


}
